package com.dhecp.project.storage.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.core.utils.ReadExcel;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.business.service.ProductActiveService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.service.OperateCompanyApplyService;
import com.dhecp.project.storage.domain.GoodsAllocation;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockOpe;
import com.dhecp.project.storage.service.GoodsAllocationService;
import com.dhecp.project.storage.service.StockControlService;
import com.dhecp.project.storage.service.StockOpeService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: kjecp
 * @description: 库存修改单
 * @author: hlf
 * @create: 2022-09-01 17:23
 */
@Controller
@RequestMapping("/storage/stockope")
public class StockOpeController extends BaseModuleController {

    private String prefix = "storage/stockope";
    private String moduleTable = ModuleTable.STOCK_OPE;
    @Autowired
    private GoodsAllocationService goodsAllocationService;
    @Autowired
    private OperateCompanyApplyService operateCompanyApplyService;
    @Autowired
    private ProductActiveService productActiveService;
    @Autowired
    private StockOpeService storageService;
    @Autowired
    private StockControlService stockControlService;

    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private BaseInfoSimpleService baseInfoSimpleService;

    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-05-09 11:39
     */
    @RequiresPermissions("storage:stockope:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockOpe()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/stockope"); //页面路径

        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "stockope");
        return mv;
    }

    /**
     * @Description: 打开制单页
     * @Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: xdh
     * @date: 2023-03-07 11:39
     */
    @RequiresPermissions("storage:stockope:view")
    @GetMapping("/add")
    public ModelAndView addPage(@RequestParam Map<String, Object> params) {
    	
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockOpe()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>();            //生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>();    //隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        StockOpe entity = new StockOpe();
        
        // 初始化单据
        entity.setBid(storageService.getBidForAdd());
        
        try {
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
            params.put("getFieldAttributesType", "pagenotingrid");    //非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                for (SysDictionaryForPageField dicFields : dicFieldsList) {
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    
                    Map<String, Object> infoData = TypeUtils.entityToMap(entity);

                    fieldsListMap.put("fieldContent", infoData.get(fieldsListMap.get("fields")));

                    if (fieldsListMap.get("fieldFrontType") == null) {
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }


                    //如果有下拉控件，则根据配置获取对应下拉待选内容
                    List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    String fieldFrontType = dicFields.getFieldFrontType();
                    String fieldSearchType = dicFields.getFieldSearchType();
                    String fieldFrontSave = dicFields.getFieldFrontSave();
                    String fieldFrontShow = dicFields.getFieldFrontShow();
                    if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")) {
                        if (fieldSearchType != null && !"".equals(fieldSearchType)) {
                            if (fieldFrontSave == null || "".equals(fieldFrontSave)) {
                                fieldFrontSave = "vid";
                            }
                            if (fieldFrontShow == null || "".equals(fieldFrontShow)) {
                                fieldFrontShow = "vname";
                            }
                            dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType, fieldFrontSave, fieldFrontShow);
                        }
                    }
                    fieldsListMap.put("dropdownList", dropdownList);
                    if ((Integer) fieldsListMap.get("fieldFrontTop") == 1) {    //显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    } else {    //隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);                //显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);    //隐藏的字段
        mv.addObject("StockOpe", entity);    //字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/stockope_add_all");
//        mv.setViewName(prefix + "/stockope_add");
        return mv;

    }
    
    /**
     * 获取商品名称
     */
    @PostMapping("/getProductNameByCode")
    @ResponseBody
    public AjaxResult getProductNameByCode(String productCode){
		
    	AjaxResult ajaxResult = new AjaxResult();
        try {
        	ProductActive productActive = productActiveService.queryProductActiveByCode(productCode);
        	if (productActive == null) {
        		ProductActiveComponent productActiveComponent = productActiveService.querySingleProductActiveComponentByCode(productCode);
        		if (productActiveComponent == null) {
					return AjaxResult.error("系统中无此编码");
				} else {
					return AjaxResult.success(productActiveComponent.getName());
				}
        	} else {
				return AjaxResult.success(productActive.getName());
        	}
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 打开制单页
     * @Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: xdh
     * @date: 2023-03-07 11:39
     */
    @RequiresPermissions("storage:stockope:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockOpe()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>();            //生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>();    //隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        StockOpe entity = new StockOpe();
        try {
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            entity = storageService.findByGuid(params);
            if (dictionaryForFieldMap.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
            params.put("getFieldAttributesType", "pagenotingrid");    //非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()) {
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            } else {
                for (SysDictionaryForPageField dicFields : dicFieldsList) {
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    if (entity == null) {
                        ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                        entity = new StockOpe();
                        entity.setBid(moduleNidAndBid.getBid());

                    }
                    Map<String, Object> infoData = TypeUtils.entityToMap(entity);

                    fieldsListMap.put("fieldContent", infoData.get(fieldsListMap.get("fields")));

                    if (fieldsListMap.get("fieldFrontType") == null) {
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }


                    //如果有下拉控件，则根据配置获取对应下拉待选内容
                    List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    String fieldFrontType = dicFields.getFieldFrontType();
                    String fieldSearchType = dicFields.getFieldSearchType();
                    String fieldFrontSave = dicFields.getFieldFrontSave();
                    String fieldFrontShow = dicFields.getFieldFrontShow();
                    if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")) {
                        if (fieldSearchType != null && !"".equals(fieldSearchType)) {
                            if (fieldFrontSave == null || "".equals(fieldFrontSave)) {
                                fieldFrontSave = "vid";
                            }
                            if (fieldFrontShow == null || "".equals(fieldFrontShow)) {
                                fieldFrontShow = "vname";
                            }
                            dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType, fieldFrontSave, fieldFrontShow);
                        }
                    }
                    fieldsListMap.put("dropdownList", dropdownList);
                    if ((Integer) fieldsListMap.get("fieldFrontTop") == 1) {    //显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    } else {    //隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);                //显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);    //隐藏的字段
        mv.addObject("StockOpe", entity);    //字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/stockope_edit");
        return mv;

    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:stockope:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<StockOpe> list = new ArrayList<StockOpe>();
        try {
            list = storageService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 数据导出Excel
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:stockope:export")
    @Log(title = "库存修改单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockOpe());

        List<StockOpe> list = storageService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<StockOpe> util = new ExportExcelUtils<StockOpe>(moduleTable, new StockOpe());
        return util.exportExcel(list, fieldList, "库存修改单", "export");
    }

    /**
     * @Description: 导出Excel导入模板
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:stockope:import")
    @Log(title = "库存修改单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockOpe());

        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<StockOpe> util = new ExportExcelUtils<StockOpe>(moduleTable, new StockOpe());
        return util.exportExcel(null, fieldList, "库存修改单导入模板", "template");
    }
    
    /**
     * 新增商品库——数据提交
     * @param params
     * @return
     * @author DH-Xxj
     */
    @Log(title = "新增库存修改单(入库)", businessType = BusinessType.INSERT)
    @RequiresPermissions("storage:stockope:add")
    @PostMapping("/addpostIn")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addpostIn(String bid,
			String vGsBm,
			String vGsMc,
			String vGsJc,
			String productCode, Integer productNum,
			String locationHw,
			String locationKq,
			String locationArea,
			String remark
			){
		
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.addStockOpeIn(bid, vGsBm, vGsMc, vGsJc, productCode, productNum, locationHw, locationKq, locationArea, remark);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 新增商品库——数据提交
     * @param params
     * @return
     * @author DH-Xxj
     */
    @Log(title = "新增库存修改单(出库)", businessType = BusinessType.INSERT)
    @RequiresPermissions("storage:stockope:add")
    @PostMapping("/addpostOut")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addpostOut(String bid, String guidStockControl, Integer productNum, String remark){
		
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.addStockOpeOut(bid, guidStockControl, productNum, remark);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 保存数据
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions(value = {"storage:stockope:edit", "storage:stockope:delete"}, logical = Logical.OR)
    @Log(title = "库存修改单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = storageService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 批量导入表格
     * @Author: xdh
     * @date: 2023-03-07 11:39
     */
    @GetMapping("/toImportBatch")
    public ModelAndView toImportBatch() {
    	
        ModelAndView mv = this.getModelAndView();
        
        mv.setViewName(prefix + "/toImportBatch");
        return mv;

    }

    @PostMapping("/uploadAndReadExcelBatchImport")
    @ResponseBody
	public AjaxResult uploadAndReadExcelBatchImport(@RequestParam("file") MultipartFile uploadfile) throws Exception {
    	
    	// 运营公司MAP
    	List<OperateCompanyApply> listOperateCompanyApply = operateCompanyApplyService.listAllOn();
    	Map<String, OperateCompanyApply> MAP_COMPANY = new HashMap<String, OperateCompanyApply>();
    	for(OperateCompanyApply entity : listOperateCompanyApply) {
    		MAP_COMPANY.put(entity.getvGsBm(), entity);
    	}
    	
    	// 货位MAP
    	List<GoodsAllocation> listGoodsAllocation = null;
    	{
    		Map<String, Object> params = new HashMap<String, Object>();
            params.put("moduleTable", ModuleTable.GOODS_ALLOCATION);
    		listGoodsAllocation = goodsAllocationService.queryList(params);
    	}
    	Map<String, GoodsAllocation> MAP_GoodsAllocation = new HashMap<String, GoodsAllocation>();
    	for(GoodsAllocation entity : listGoodsAllocation) {
    		// 货位唯一码：所在仓库-库区-货位
    		String hwUk = entity.getWarehouseAddress() + "-" + entity.getGoodsArea() + "-" + entity.getGoodsAllocation();
    		
    		MAP_GoodsAllocation.put(hwUk, entity);
    	}

		try {
			InputStream fileInputStream = uploadfile.getInputStream();
//	        BufferedInputStream bis = new BufferedInputStream(fileInputStream);
			
			// 文件初始名
			String sourceFilename = uploadfile.getOriginalFilename();
	    	if (!sourceFilename.endsWith(".xlsx")) {
				return AjaxResult.error("请按照模板xlsx进行导入");
			}
			List<List<String>> data = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			
			List<TableDto.RowDto> rows = new ArrayList<TableDto.RowDto>();
			if (rows != null && rows.size() > 300) {
				return AjaxResult.error("导入数量不能超过300条");
			}
			for (int i = 1, index = 1; data != null && i < data.size(); i++) {
				List<String> row = data.get(i);
				
				Integer num = Integer.parseInt(row.get(2).replace(".0", ""));
				
				if (num > 0) {
					String guid = row.get(0);
					// 入库
					String codeProduct = row.get(1);
					
					String codeCompany = row.get(6);
					OperateCompanyApply operateCompanyApply = MAP_COMPANY.get(codeCompany);
					if (operateCompanyApply == null) {
						continue;
					}
					String nameCompany = operateCompanyApply.getvGsMc();
					String nameCompanyShort = operateCompanyApply.getvGsJc();

					String locationArea = row.get(3);
					String locationKq = row.get(4);
					String locationHw = row.get(5);
					String hwUk = locationArea + "-" + locationKq + "-" + locationHw;
					GoodsAllocation goodsAllocation = MAP_GoodsAllocation.get(hwUk);
					if (goodsAllocation == null) {
						continue;
					}
					
					String remark = row.get(7);
					TableDto.RowDto rowDto = new TableDto.RowDto(index, guid, codeProduct, codeCompany, nameCompany, nameCompanyShort, num, locationHw, locationKq, locationArea, remark);
					rows.add(rowDto);
				} else {
					// 出库
					String guid = row.get(0);
					StockControl stockControl = stockControlService.findByGuid(guid);
					if (stockControl == null) {
						return AjaxResult.error("唯一标识【" + guid + "】有误");
					}
					
					String codeProduct = stockControl.getProductCode();
					
					String codeCompany = stockControl.getvGsBm();
					String nameCompany = stockControl.getvGsMc();
					String nameCompanyShort = stockControl.getvGsJc();
					
					String locationHw = stockControl.getvHw();
					String locationKq = stockControl.getvKq();
					String locationArea = stockControl.getgDepot();
					String remark = row.get(7);
					TableDto.RowDto rowDto = new TableDto.RowDto(index, guid, codeProduct, codeCompany, nameCompany, nameCompanyShort, num, locationHw, locationKq, locationArea, remark);
					rows.add(rowDto);
				}
				index++;
			}
			TableDto dto = new TableDto(rows);
			return AjaxResult.success(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("数据有误，请联系客服");
		}
	}
	@Data
	@AllArgsConstructor
	public static class TableDto{
		private List<RowDto> rows; // 货件清单数组
		
		@Data
		@AllArgsConstructor
		public static class RowDto {
			private int index; // 序号
			private String guid; // 唯一标识
			private String codeProduct; // 商品编码
			private String codeCompany; // 公司编码
			private String nameCompany; // 公司名称
			private String nameCompanyShort; // 公司简称
			private Integer num; // 变动数量
			private String locationHw; // 货位编码
			private String locationKq; // 库区编码
			private String locationArea; // 所在地区
			private String remark; // 备注
		}
	}
    
    /**
     * 批量新增商品库——数据提交
     * @param params
     * @return
     * @author DH-Xxj
     */
    @Log(title = "批量新增库存修改单", businessType = BusinessType.INSERT)
    @RequiresPermissions("storage:stockope:add")
    @PostMapping("/importBatch")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult importBatch(String detailArr){
    	
    	if (detailArr == null || detailArr.length() == 0) {
			return AjaxResult.error("导入出错，请联系技术");
		}
    	JSONArray detailJA = JSON.parseArray(detailArr);
    	for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

	    	JSONObject paramJO = new JSONObject();
	        paramJO.put("moduleTable", moduleTable);
	        paramJO.put("entity", new StockOpe());
	        try {

	        	String productCode = detailJO.getString("codeProduct");

        		Integer productNum = detailJO.getInteger("num");
				String bid = storageService.getBidForAdd();
				String remark = detailJO.getString("remark");
	        	if (detailJO.getInteger("num") > 0) {
	        		String vGsBm = detailJO.getString("codeCompany");
	        		String vGsMc = detailJO.getString("nameCompany");
	        		String vGsJc = detailJO.getString("nameCompanyShort");
	        		String locationHw = detailJO.getString("locationHw");
	        		String locationKq = detailJO.getString("locationKq");
	        		String locationArea = detailJO.getString("locationArea");
	        		storageService.addStockOpeIn(bid, vGsBm, vGsMc, vGsJc, productCode, productNum, locationHw, locationKq, locationArea, remark);
				} else if (detailJO.getInteger("num") < 0) {
					String guidStockControl = detailJO.getString("guid");
					storageService.addStockOpeOut(bid, guidStockControl, productNum, remark);
				}
	        
	        }catch (Exception e) {
	        	e.printStackTrace();
	            return AjaxResult.error(this.getExceptionMessage(e));
	        }
		}
        return AjaxResult.success("操作成功");
    }

}